package com.lx.java8;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

import org.junit.Test;

public class FunctionDriver {

	/**
	 * Consumer接口
	 * @param s
	 * @param c
	 */
	public void consumer(String s, Consumer<String> c) {
		c.accept(s);
	}

	@Test
	public void testConsumer() {
		consumer("GOGO", (s) -> System.out.println("hello," + s));
	}

	/**
	 * Supplier，产生n个数字
	 * @return
	 */
	public List<Integer> supplier(int count, Supplier<Integer> s) {
		List<Integer> iList = new ArrayList<>();
		for (int i = 0; i < count; i++) {
			Integer v = s.get();
			iList.add(v);
		}
		return iList;
	}

	@Test
	public void testSupplier() {
		Random r = new Random();
		List<Integer> iList = supplier(10, () -> r.nextInt(100));
		for (Integer i : iList) {
			System.out.println(i);
		}
	}

	/**
	 * Predicate
	 * @param s
	 * @param p
	 * @return
	 */
	public boolean predicate(String s, Predicate<String> p) {
		return p.test(s);
	}

	@Test
	public void testPredicate() {
		boolean b = predicate("hello", (s) -> s.length() > 3); //判断字符串的商都是否大于3
		System.out.println(b);
	}

	/**
	 * Function
	 * @param s
	 * @param f
	 * @return
	 */
	public Integer function(String s, Function<String, Integer> f) {
		return f.apply(s);
	}

	@Test
	public void testFunction() {
		String a = "123";
		System.out.println(20 + function(a, m -> Integer.valueOf(m)));
	}
	
	/**
	 * 自定义函数式接口
	 */
	public String handlerString(String s, SelfDefine<String, String> myFunc) {
		return myFunc.handleValue(s);
	}

	@Test
	public void testSelfDefine() {
		String s = handlerString("hello ,Google", x -> x.toUpperCase());
		System.out.println(s);
		String s2 = handlerString("hello ,Google", x -> x.toLowerCase());
		System.out.println(s2);
	}

}
